package cn.gson.crm.controller.beforesale;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;

import cn.gson.crm.model.dao.CustomerDao;
import cn.gson.crm.model.dao.EmployeeDao;
import cn.gson.crm.model.dao.CareCusDao;
import cn.gson.crm.model.entity.CareCustomer;
import cn.gson.crm.model.entity.Customer;
import cn.gson.crm.model.entity.Employee;
import cn.gson.crm.model.mapper.CustomerMapper;

@Controller
@RequestMapping("/carecus")
public class CareCusController {

	@Autowired
	CareCusDao carecusDao;
	
	@Autowired
	CustomerMapper cusMapper;
	
	@Autowired
	CustomerDao cusDao;
	
	@Autowired
	EmployeeDao empDao;
	
	@RequestMapping
	public String init() {
		return "beforesale/carecus/carecus";
	}
	
	@RequestMapping("list")
	@ResponseBody
	public Map<String, Object> list(@RequestParam(defaultValue = "1") int page,
			@RequestParam(defaultValue = "10") int rows,
			HttpServletRequest req
			){
		Employee emp = (Employee) req.getSession().getAttribute("employee");
		PageRequest pr = new PageRequest(page - 1, rows,new Sort(Direction.DESC,"id"));
		Page<CareCustomer> carecus = null;
		//销售员显示所有与当前登录用户相关且未删除的客户线索
		if (emp.getRole().getRoleName().equals("销售员")) {
			carecus = carecusDao.findAllByEmployeeAndIsDelete(emp,false,pr);
		}else {
			//管理者显示所有未删除的客户关怀线索
			carecus = carecusDao.findAllByIsDelete(false, pr);
		}
		Map<String, Object> data = new HashMap<>();
		data.put("rows", carecus.getContent());
		data.put("total", carecus.getTotalElements());
		return data;
	}
	
	/**
	 * 根据是否有Id判断是编辑还是新建
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping({"carecusform","carecusform/{id}"})
	public String cusForm(@PathVariable(required=false) Long id,Model model){
		//如果是编辑，则将信息赋到页面去
		if (id != null) {
			model.addAttribute("c",carecusDao.findOne(id));
		}
		return "beforesale/carecus/carecusform";
	}
	
	
	/**
	 * 保存客户关怀记录
	 * @param carecus
	 * @param contacts
	 * @param br
	 * @return
	 */
	@RequestMapping("/save")
	@ResponseBody
	@Transactional
	public JSONObject save(@Valid CareCustomer carecus,
			@Valid Long cusid,
			HttpSession session,
			BindingResult br) {
		JSONObject result = new JSONObject();
		if (br.hasErrors()) {
			result.put("err", "校验失败！");
		}else {
			//客户外键
			Customer cus = cusDao.findOne(cusid);
			//员工外键(这里是临时这么用，登录以后可以使用session里读取出来使用)
			Employee emp = (Employee)session.getAttribute("employee");
			if (cus == null) {
				result.put("err", "没有此联系人。");
			}else {
				carecus.setCustomer(cus);
				carecus.setEmployee(emp);
				carecusDao.save(carecus);
				result.put("success", true);
			}	
		}
		return result;
	}
	
	
	/**
	 * 数据库并没有删除，只是更改了删除状态这个字段，使其不显示
	 * @param id
	 * @return
	 */
	@GetMapping("delete/{id}")
	@ResponseBody
	public Map<String, Object> delete(@PathVariable Long id){
		Map<String, Object> data = new HashMap<>();
		
		try {
			CareCustomer carecus = carecusDao.findOne(id);
			carecus.setDelete(true);
			carecusDao.save(carecus);
			data.put("success", true);
		} catch (Exception e) {
			e.printStackTrace();
			data.put("success", false);
			data.put("errorMsg", e.getMessage());
		}
		return data;
	}
	
	/**
	 * 根据id和姓名查询联系人
	 * @param seacont
	 * @return
	 */
	@PostMapping("search/{seacont}")
	@ResponseBody
	public List<Customer> search(@PathVariable String seacont,Model model){

		List<Customer> cus = new ArrayList<>();
		cus = cusMapper.searchCon(seacont);
		return cus;
	}
}
